from http.cookiejar import CookieJar
import os.path
import pickle

import PublicConstant


class Settings:
    def __init__(self, load_from_file: bool = True):
        self.allow_r18: bool = True
        self.allow_normal: bool = True
        self.allow_ai: bool = True
        self.proxies: dict[str, str] | None = None
        self.like_num_threshold: int = 0

        if load_from_file:
            self.load_settings_from_file()

    def __repr__(self) -> str:
        return f'Settings: {{\n' \
               f'    AllowR18: {self.allow_r18},\n' \
               f'    AllowNormal: {self.allow_normal},\n' \
               f'    AllowAI: {self.allow_ai}, \n' \
               f'    Proxies: {self.proxies},\n' \
               f'    LikeNumThreshold: {self.like_num_threshold}\n' \
               f'}}'

    def load_settings_from_file(self):
        if os.path.exists(PublicConstant.settings_profile):
            with open(PublicConstant.settings_profile, 'rb') as f:
                try:
                    obj = pickle.load(f)
                    self.allow_r18 = obj['allow_r18']
                    self.allow_normal = obj['allow_normal']
                    self.allow_ai = obj['allow_ai']
                    self.proxies = obj['proxies']
                    self.like_num_threshold = obj['like_num_threshold']
                except (KeyError, EOFError):
                    print(
                        f'Setting profile `{PublicConstant.settings_profile}` may be broken. '
                        f'Loading default settings...'
                    )
                    self.allow_r18 = True
                    self.allow_normal = True
                    self.allow_ai = True
                    self.proxies = None
                    self.like_num_threshold = 0
        else:
            print(
                f'Setting profile `{PublicConstant.settings_profile}` may be missing. '
                f'Loading default settings...'
            )
            self.allow_r18 = True
            self.allow_normal = True
            self.allow_ai = True
            self.proxies = None
            self.like_num_threshold = 0

    def save_settings_to_file(self):
        with open(PublicConstant.settings_profile, 'wb') as f:
            obj = dict()
            obj['allow_r18'] = self.allow_r18
            obj['allow_normal'] = self.allow_normal
            obj['allow_ai'] = self.allow_ai
            obj['proxies'] = self.proxies
            obj['like_num_threshold'] = self.like_num_threshold
            pickle.dump(obj, f)


if __name__ == '__main__':
    test = Settings()
    print(test)
    # test.allow_ai = False
    # test.proxies = {
    #     'http': 'http://127.0.0.1:20171',
    #     'https': 'http://127.0.0.1:20171'
    # }
    # test.save_settings_to_file()

